<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\InviteOp;
use App\Http\Controllers\Controller;
use App\Model\CoinLog;
use App\Model\Guild\GuildHost;
use App\Model\Log\AdminInviteLog;
use App\Model\InviteRewardLog;
use App\Model\PayOrder;
use App\Model\User;
use App\Model\AdminInviteReward;
use App\Model\UserCoin;
use App\Model\UserProfile;
use App\Util\ComUtil;
use App\Util\InfoUtil;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Form;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Model;

class UserInviteController extends Controller
{
    use ModelForm;

    /**
     * 用户列表
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('邀请关系列表');
            $guildHosts = GuildHost::getAllHosts();
            $content->body($this->userList($guildHosts));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('绑定');
            $content->description('');
            $content->body($this->form());
        });
    }

    /**
     * 用户列表
     * @return Grid
     */
    protected function userList($guildHosts)
    {
        $grid = new Grid(new UserProfile());
        $where = [
            ['invite_code', '<>', '']
        ];
        $grid->model()->where($where)->orderBy('user_id', 'desc');
        $grid->invite_code('邀请人用户ID（用户输入）');
        $grid->inviteUser()->nick_name('邀请人昵称');
//        $grid->is_guild('是否代理女用户')->display(function ($data) use ($guildHosts) {
//            if (!$this->inviteUser) return '-';
//            $inviterId = $this->inviteUser->user_id;
//            return isset($guildHosts[$inviterId]) ? $guildHosts[$inviterId] : '';
//        });
        $grid->inviteUser()->gender('邀请人性别')->display(function ($gender) {
            return $gender == 1 ? '男' : ($gender == 0 ? '女' : '-');
        });
        $grid->inviteUser()->role('邀请人角色')->display(function ($role) {
            switch ($role) {
                case UserProfile::ROLE_HOST:
                    return '女用户';
                case UserProfile::ROLE_USER:
                    return '普通用户';
            }
            return '-';
        });
        $grid->inviteUser()->phone('邀请人手机号')->display(function () {
            if (!$this->inviteUser) return '-';
            $user = User::find($this->inviteUser->user_id);
            return $user ? $user->phone : '';
        });
        // $grid->inviteUser()->user_id('邀请人内部ID');
        // $grid->hiddenColumns = ['user_id', 'inviteUser.user_id'];
        $grid->user_profile_id('被邀请人用户ID');
        $grid->nick_name('被邀请人昵称');
        // $grid->user_id('被邀请人内部ID');
        $grid->gender('被邀请人性别')->display(function ($gender) {
            return $gender == 1 ? '男' : ($gender == 0 ? '女' : '-');
        });
        $grid->role('被邀请人角色')->display(function ($role) {
            return $role == UserProfile::ROLE_HOST ? '女用户' : '普通用户';
        });
        $grid->userItem()->phone('被邀请人手机号');

        $grid->created_at('邀请时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->rewardCoin('邀请奖励（金币）')->display(function ($model) {
            $inviter = $this->inviteUser ? $this->inviteUser->user_id : 0;
            $coin = InviteRewardLog::getInviteCoin($inviter, $this->user_id);
            return $coin;
        })->modal('奖励记录', function ($model) {
            $where = [
                'user_id' => $this->inviteUser ? $this->inviteUser->user_id : 0,
                'invited_user_id' => $this->user_id,
            ];
            $logs = InviteRewardLog::where($where)->orderBy('id', 'desc')->take(100)->get()->map(function ($data) {
                return $data->only(['created_at', 'reward_type', 'reward_coin']);
            })->toArray();
            array_walk($logs, function (&$log) {
                $log['reward_type'] = InviteRewardLog::TYPE[$log['reward_type']] ?? '未知';
            });
            return new Table(['奖励时间', '奖励类型', '奖励金币'], $logs);
        });
        // $this->bindTableExpan();

        //禁用导出
        $grid->disableExport();
        //禁用新增
        if (!(Admin::user()->inRoles(['administrator'])) || Admin::user()->getAuthIdentifier() != 46){
//            $grid->disableCreateButton();
        }
        // $grid->disableCreation();
        // $grid->disableActions();
        //禁用行选择
        $grid->disableRowSelector();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('inviteUser.user_profile_id', '邀请人ID');
                $filter->equal('user_profile_id', '被邀请人ID');
                $filter->equal('gender', '被邀请人性别')->select([0 => '女', 1 => '男', -1 => '其他']);
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('userItem.phone', '被邀请人手机号');
                $filter->between('created_at', '邀请时间')->datetime();
            });
        });

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
            $actions->append(new InviteOp(
                $actions->getKey(),
                $actions->row,
                'invite/op'
            ));
        });
        return $grid;
    }

    function op()
    {
        $id = request('id');
        $action = request('action');
        switch ($action) {
            case 'unbind':
                UserProfile::where('user_profile_id', $id)->limit(1)->update(['invite_code' => '']);
                break;
            //邀请奖励补发
            case 'reward':
                $userProfile = UserProfile::query()->where('user_profile_id', $id)->first();
                if (empty($userProfile)) {
                    return ['ret' => -1, 'message' => '用户不存在！'];
                }

                $invite = UserProfile::query()->where('user_profile_id', $userProfile->invite_code)->first();

                if (empty($invite)) {
                    return ['ret' => -1, 'message' => '邀请人不存在！'];
                }

                //补发充值邀请(一天)
                $start_time = date('Y-m-d H:i:s', strtotime('-1 days'));
                $end_time = date('Y-m-d H:i:s');
                $rechargeCoin = PayOrder::query()->where([
                    ['subject_type', '=', 'recharge'],
                    ['user_id', '=', $userProfile->user_id],
                    ['status', '=', 1],
                    ['created_at', '<=', $end_time],
                    ['created_at', '>=', $start_time],
                ])->sum('recharge_coin');

                $rewardCoinR = 0;
                if ($rechargeCoin > 0) {
//                    $url = config('busi.api_url') . 'coin/invite_reward';
//                    $ret = ComUtil::httpReq($url, ['user_id' => (string)$invite->user_id]);
//                    $ret = json_decode($ret, true);
//                    if ($ret['result'] !== 0) {
//                        return ['ret' => -1, 'message' => '获取分成比例失败！'];
//                    }
                    $rewardCoin = round($rechargeCoin * env('INVITE_RECHARGE_PERCENT', 0.2), 1);

                    //查询已经奖励过的邀请金额
                    $oldReward = InviteRewardLog::query()->where([
                        ['user_id', '=', $invite->user_id],
                        ['invited_user_id', '=', $userProfile->user_id],
                        ['reward_type', '=', InviteRewardLog::TYPE_RECHARGE],
                        ['created_at', '<=', $end_time],
                        ['created_at', '>=', $start_time],
                    ])->sum('reward_coin');

                    $rewardCoinR = round($rewardCoin - $oldReward, 1);

                    if ($rewardCoinR > 0) {
                        //邀请记录
                        InviteRewardLog::addRecord($invite->user_id, $userProfile->user_id, $rewardCoinR, InviteRewardLog::TYPE_RECHARGE);
                        //更新收入账户
                        $remainCoin = UserCoin::gainIncome($invite->user_id, $rewardCoinR);

                        $coinLogFrom = CoinLog::FROM_INVITE_RECHARGE;

                        //账户流水
                        CoinLog::addIncome($invite->user_id, $rewardCoinR, $coinLogFrom, $remainCoin, '', '', $userProfile->user_id);
                    }
                }

                //增加邀请
                $adminInviteRewardModel = new AdminInviteReward();
                $adminInviteRewardModel->user_id = $invite->user_id;
                $adminInviteRewardModel->invited_user_id = $userProfile->user_id;
                $adminInviteRewardModel->reward_coin = $rewardCoinR;
                $adminInviteRewardModel->admin_id = Admin::user()->id;
                $adminInviteRewardModel->save();
        }
        return ['ret' => 0, 'message' => '操作成功！'];
    }

    /**
     * Make a form builder.
     * @return Form
     */
    protected function form($mode = '', $id = '')
    {
        return Admin::form(UserProfile::class, function (Form $form) use ($mode, $id) {
            $form->text('user_profile_id', '被邀请人用户ID（多个用,隔开）')->required();
            $form->text('invite_profile_id', '邀请人ID')->required();
            $form->saving(function (Form $form) {
                $profileIds = trim($form->user_profile_id);
                $profileIds = explode(",", $profileIds);

                $inviteCode = (int)trim($form->invite_profile_id);
                if(empty(array_diff([$inviteCode],$profileIds))){
                    return InfoUtil::adminErr("输入消息有误");
                }

                //判断用户邀请人是否存在
                if(!UserProfile::where('user_profile_id',$inviteCode)->exists()){
                    return InfoUtil::adminErr("邀请人有误，请重新确认~");
                }

                foreach ($profileIds as &$profileId) {
                    $profileId = (int)trim($profileId);
                    $check = UserProfile::where('user_profile_id', $profileId)->first();
                    if (!$check || $check->invite_code) {
                        return InfoUtil::adminErr("{$profileId}用户有绑定邀请，或者信息有误！");
                    }

                    //判断邀请人和被邀请人是用一人
                    if($inviteCode == $profileId){
                        return InfoUtil::adminErr("{$profileId}邀请人和被邀请人是用一人！");
                    }

                    //判断是否有
                    $guildHost = GuildHost::where('host_user_id',$check->user_id)->where('status',1)->first();
                    if(!empty($guildHost)){
                        return InfoUtil::adminErr("{$profileId}该用户已绑定推广员！");
                    }
                }

                UserProfile::whereIn('user_profile_id', $profileIds)->limit(count($profileIds))->update(['invite_code' => $inviteCode]);
                AdminInviteLog::create([
                    'invited_profile_id' => implode(',', $profileIds),
                    'inviter_profile_id' => $inviteCode,
                    'admin_id' => Admin::user()->id
                ]);
                return InfoUtil::adminSuc("绑定成功！");
            });
            $form->tools(function (Form\Tools $tools) {
                $tools->disableList();
                $tools->disableDelete();
                $tools->disableView();
                $tools->disableView();
            });
        });
    }
}
